from django import forms
from web.models import users
from django.forms.models import model_to_dict
from web.api import result
from django.db.models import Q
from functools import wraps

class UserModelForm(forms.ModelForm):
    class Meta:
        model = users
        # 除了user_id,其他字段都显示
        fields = "__all__"
        exclude = ["user_id"]

# 装饰器：检查请求方法
def require_http_methods(methods):
    def decorator(func):
        @wraps(func)
        def wrapper(request, *args, **kwargs):
            if request.method not in methods:
                return result.result(400, f"请求方式错误，仅支持 {', '.join(methods)}")
            return func(request, *args, **kwargs)
        return wrapper
    return decorator

# 装饰器：验证基本参数
def validate_user_params(require_password=True):
    def decorator(func):
        @wraps(func)
        def wrapper(request, *args, **kwargs):
            try:
                # 获取参数
                data = request.POST if request.method == "POST" else request.GET
                account = data.get("account")
                password = data.get("password") if require_password else None
                platform = data.get("platform")
                
                # 验证参数
                params = [account, platform]
                if require_password:
                    params.append(password)
                
                if not all(params):
                    return result.result(400, "请填写完整的信息")
                
                try:
                    platform = int(platform)
                except ValueError:
                    return result.result(400, "平台号必须是数字")
                
                # 将验证后的参数传递给原函数
                return func(request, account=account, password=password, platform=platform, *args, **kwargs)
            except Exception as e:
                return result.result(400, "参数验证失败", str(e))
        return wrapper
    return decorator

# 用户注册
@require_http_methods(["POST"])
def user_register(request):
    form = UserModelForm(request.POST)
    try:
        if form.is_valid():
            form.save()
            return result.result(200, "注册成功", model_to_dict(form.instance))
        error_info = result.Forms_GetError(form)
        return result.result(400, "注册失败", f"{error_info[1]} {error_info[0]}")
    except ValueError as e:
        return result.result(400, "注册失败", str(e))

# 用户登录
@require_http_methods(["POST"])
@validate_user_params()
def user_login(request, account, password, platform):
    try:
        user = users.objects.filter(
            account=account,
            password=password,
            platform=platform
        ).first()
        
        if user:
            return result.result(200, "登录成功", model_to_dict(user))
        return result.result(400, "账号或密码错误")
    except Exception as e:
        return result.result(400, "登录失败", str(e))

# 更新用户密码
@require_http_methods(["POST"])
@validate_user_params()
def user_update_password(request, account, password, platform):
    try:
        new_password = request.POST.get("new_password")
        if not new_password:
            return result.result(400, "请提供新密码")

        user = users.objects.filter(
            account=account,
            password=password,
            platform=platform
        ).first()

        if not user:
            return result.result(400, "用户不存在或原密码错误")

        user.password = new_password
        user.save()
        return result.result(200, "更新成功", model_to_dict(user))
    except ValueError as e:
        return result.result(400, "更新失败", str(e))

# 删除用户
@require_http_methods(["POST"])
@validate_user_params()
def user_delete(request, account, password, platform):
    try:
        user = users.objects.filter(
            account=account,
            password=password,
            platform=platform
        ).first()

        if not user:
            return result.result(400, "用户不存在或信息错误")

        user.delete()
        return result.result(200, "删除成功")
    except Exception as e:
        return result.result(400, "删除失败", str(e))

# 查询单个用户
@require_http_methods(["POST"])
@validate_user_params()
def user_query(request, account, password, platform):
    try:
        user = users.objects.filter(
            account=account,
            password=password,
            platform=platform
        ).first()

        if user:
            return result.result(200, "查询成功", model_to_dict(user))
        return result.result(400, "用户不存在")
    except Exception as e:
        return result.result(400, "查询失败", str(e))

# 查询平台下的所有用户
@require_http_methods(["GET"])
@validate_user_params(require_password=False)
def platform_users(request, account=None, password=None, platform=None):
    try:
        users_list = users.objects.filter(platform=platform)
        users_data = [model_to_dict(user) for user in users_list]
        return result.result(200, "查询成功", users_data)
    except Exception as e:
        return result.result(400, "查询失败", str(e))




